/*
 * @Author: jianfanfan 1217572833@qq.com
 * @Date: 2025-03-19 17:41:14
 * @LastEditors: jianfanfan 1217572833@qq.com
 * @LastEditTime: 2025-03-21 14:44:59
 * @FilePath: \guozaoke\src\node\node.module.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Module, OnModuleInit } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Node } from './entities/node.entity';
import { Post } from './entities/post.entity';
import { Reply } from './entities/reply.entity';
import { NodeService } from './node.service';
import { NodeController } from './node.controller';
import { PostsService } from './post.service';
import { PostController } from './post.controller';
import { JwtModule } from '@nestjs/jwt';
import { AuthModule } from '../auth/auth.module';
import { User } from '../auth/entities/user.entity';
import { CacheModule } from '../common/cache.module';
import { LoggerModule } from '../common/logger/logger.module';
import { initialNodes } from '../config/nodes.init';

@Module({
  imports: [
    TypeOrmModule.forFeature([Node, Post, Reply, User]),
    JwtModule.register({
      secret: 'secret',
      signOptions: { expiresIn: '1d' },
    }),
    AuthModule,
    LoggerModule,
    CacheModule,
  ],
  providers: [NodeService, PostsService],
  controllers: [NodeController, PostController],
  exports: [TypeOrmModule, NodeService],
})
export class NodeModule implements OnModuleInit {
  constructor(private readonly nodeService: NodeService) {}

  async onModuleInit() {
    // 初始化节点数据
    await this.initializeNodes(initialNodes);
  }

  private async initializeNodes(nodes: any[]) {
    // 先创建所有顶级节点
    for (const node of nodes) {
      try {
        // 创建顶级节点，将parentId设为null
        const topNode = await this.nodeService.createNode(
          {
            name: node.name,
            slug: node.slug,
            description: node.description,
            parentId: null, // 将顶级节点的parentId设为null
            sort: node.sort || 0,
          },
          null,
        );

        // 如果有子节点，使用新创建的顶级节点ID作为parentId创建子节点
        if (node.children && node.children.length > 0) {
          await this.createChildNodes(node.children, topNode.id);
        }
      } catch (error) {
        console.error(`Error creating node ${node.name}:`, error.message);
      }
    }
  }

  private async createChildNodes(children: any[], parentId: number) {
    for (const child of children) {
      try {
        const childNode = await this.nodeService.createNode(
          {
            name: child.name,
            slug: child.slug,
            description: child.description,
            parentId: parentId,
            sort: child.sort || 0,
          },
          parentId,
        );

        // 递归处理更深层的子节点
        if (child.children && child.children.length > 0) {
          await this.createChildNodes(child.children, childNode.id);
        }
      } catch (error) {
        console.error(
          `Error creating child node ${child.name}:`,
          error.message,
        );
      }
    }
  }
}
